package clienteServidor.infoHWSWEquipo;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

import clienteServidor.excepciones.ImposibleObtenerIPException;

public class Red {
	private String ipV4;
	private String mascara;
	private String red;
	private String broadcast;
	private String mac;
	private String nombreEquipo;

	private Red() throws SocketException, ImposibleObtenerIPException, UnknownHostException{
		InetAddress i= InetAddress.getLocalHost();

		this.setNombreEquipo(i.getHostName());

		this.setIpV4(i.getHostAddress());

		NetworkInterface ni= NetworkInterface.getByInetAddress(i);

		InterfaceAddress ia= ni.getInterfaceAddresses().get(0);
		this.setBroadcast("255.255.255.255");
		this.setMascara(ia.getNetworkPrefixLength()+"");

		byte [] bip= i.getAddress(), res= new byte[4];

		short pre= ni.getInterfaceAddresses().get(0).getNetworkPrefixLength();


		StringBuilder s= new StringBuilder();
		for(int j= 0; j < 4; j++){
			if(j < pre) res[j]= (byte) (bip[j]&377);
			else res[j]= 0;
			s.append(res[j]);
		}
		setRed(s.toString());

		byte[] aux= ni.getHardwareAddress();
		if(aux == null) throw new ImposibleObtenerIPException();
		StringBuilder sb = new StringBuilder();
		for (int j = 0; j < aux.length; j++) {
			sb.append(String.format("%02X%s", aux[j], (j < aux.length - 1) ? "-" : ""));        
		}

		setMac(sb.toString());
	}

	private static Red instancia;

	public static Red getInstancia() throws SocketException, UnknownHostException, ImposibleObtenerIPException{
		if(instancia == null) instancia= new Red();
		return instancia;
	}

	public String getIpV4() {
		return ipV4;
	}

	public String getMascara() {
		return mascara;
	}

	public String getRed() {
		return red;
	}

	public String getBroadcast() {
		return broadcast;
	}

	public String getMac() {
		return mac;
	}

	public String getNombreEquipo() {
		return nombreEquipo;
	}

	private void setNombreEquipo(String nombreEquipo) {
		this.nombreEquipo = nombreEquipo;
	}

	private void setIpV4(String ipV4) {
		this.ipV4 = ipV4;
	}

	private void setMascara(String mascara) {
		this.mascara = mascara;
	}

	private void setRed(String red) {
		this.red = red;
	}

	private void setBroadcast(String broadcast) {
		this.broadcast = broadcast;
	}

	private void setMac(String mac) {
		this.mac = mac;
	}
}
